var http=require('http');
var fs=require('fs');
var qs=require('querystring');

var items=['example'];
var temp=fs.readFileSync('./index.html').toString();

var server=http.createServer(function (req, res) {
    if('/' == req.url){
        switch(req.method){
            case 'GET':
                show(res);
                break;

            case 'POST':
                add(req,res);
                break;

            default:
                badReq(res);
        }
    }else{
        notFound(res);
    }
});
server.listen(3000,function () {
    console.log('Form port:3000',new Date());
});


//Fun
function show(res) {
    var html=temp.replace(/\{list\}/,function () {
       return items.map(function (item, i) {
           return '<li>'+i+') '+item+'</li>\n';
       }).join('');
    });
    res.setHeader('Content-type','text/html');
    res.setHeader('Content-Length',Buffer.byteLength(html));
    res.end(html);
}

function add(req, res) {
    var body='';
    req.setEncoding('utf8');
    req.on('data',function (chunk) {
        body+=chunk;
    });
    req.on('end',function () {
        console.log(body);
        var obj=qs.parse(body);
        items.push(obj.item);
        show(res);
    });
}

function notFound(res) {
    res.statusCode=404;
    res.end('Not Found.');
}

function badReq(res) {
    res.statusCode=404;
    res.end('Bad Request.');
}

